package net.xdclass.util;

import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.model.LoginUser;

import java.util.Date;

@Slf4j
public class JWTUtil {
    /**
     * 主题
     */
    private static final String SUBJECT = "xdclass";
    /**
     * 加密密钥
     */
    private static final String SECRET = "xdclass.net168";
    /**
     * 令牌前缀
     */
    private static final String TOKEN_PREFIX = "dcloud-link";
    /**
     * 过期时间7天
     */
    private static final long EXPIRED = 1000 * 60 * 60 * 24 * 7;
    /**
     * 生成JWT
     * @param loginUser
     * @return
     */
    public static String geneJsonWebToken(LoginUser loginUser){
        if(loginUser == null){
            throw new NullPointerException("对象为空");
        }
        String token = Jwts.builder().setSubject(SUBJECT)
                //配置payload
                .claim("head_img", loginUser.getHeadImg())
                .claim("account_no", loginUser.getAccountNo())
                .claim("user_name", loginUser.getUsername())
                .claim("mail", loginUser.getMail())
                .claim("phone", loginUser.getPhone())
                .claim("auth", loginUser.getAuth())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRED))
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
        token = TOKEN_PREFIX + token;
        return token;
    }

    /**
     * 解密
     */
    public static Claims checkJwt(String token){
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody();
        } catch (ExpiredJwtException e) {
            log.error("jwt解密失败");
            return null;
        }

        return claims;
    }
}
